<?php
/**
 * Date: 2018/6/27
 * Time: 19:48
 * Author: zeronlee
 */

namespace App\Models\ProjectManage;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Models\Flaw\Vuls;

class CheckOption extends Model
{
    protected $table = 'check_option';

    protected $primaryKey = 'id';

    protected $fillable = [];

    protected $guarded = [];

    public $timestamps = true;

    public $requestWhere = [];

    private $builder;

    /**
     * 插入一条记录
     * @param mixed $request
     * @return bool
     * @throws
     */
    public function addRow ($request){
        $data = $request->input();
        //转换非必填字段
        $data = $this->convertNotNull($data);
        if ( $this->create($data)->id){
            return true;
        }
        throw new \Exception('add new check option fail');
    }

    /**
     * 转换非必填字段
     * @param array $data
     * @return array
     */
    public function convertNotNull($data){
        foreach ($data as $field => $val){
            if (empty($val)){
                $data[$field] = null;
            }
        }
        return $data;
    }

    /**
     * @param $request
     * @return array
     */
    public function rules ($request){
        return [
            'name' => ['required',Rule::unique($this->table)->ignore($request->id)]
        ];
    }

    /**
     * @return array
     */
    public function messages (){
        return [
            'name.required' => '请填名称',
            'name.unique'   => '名称已存在'
        ];
    }

    /**
     * @param $request
     * @return mixed
     */
    public function validate ($request){
        return Validator::make($request->all(),
            $this->rules($request),
            $this->messages()
        );
    }

    /**
     * @param $sel
     * @param $limit
     * @param int $tId
     * @return mixed
     */
    public function lists($sel,$limit,$tId=0){

        $builder = $this->select($sel);

        $builder = $builder->when($this->requestWhere['status']==1,function($query){
                return $query->WhereNull($this->table.'.deleted_at');
            })
            ->when($this->requestWhere['status']==2,function($query){
                return $query->WhereNotNull($this->table.'.deleted_at');
            })
            ->when($this->whenWhere('keywords'),function($query){
                return $query->where($this->table.'.name','like','%'.$this->requestWhere['keywords'].'%');
            });
        $this->builder = $builder->count();
        $list =$builder->offset($limit[0])->limit($limit[1])->orderBy($this->table.'.created_at','DESC')->get();
        //统计目标应用数量
        foreach ($list as $item){
            $item->vuls_num = $this->vulNumOfCk($item->id,$tId);
        }
        return $list;
    }

    /**
     * 获取总数
     */
    public function getCount(){
        if ($this->builder){
            return $this->builder;
        } else{
            return $this->when($this->requestWhere['status']==1,function($query){
                return $query->WhereNull($this->table.'.deleted_at');
            })
                ->when($this->requestWhere['status']==2,function($query){
                    return $query->WhereNotNull($this->table.'.deleted_at');
                })
                ->when(!empty($this->whenWhere('keywords')),function($query){
                    return $query->where($this->table.'.name','like','%'.$this->requestWhere['keywords'].'%');
                })->count();
        }

    }

    /**
     * 构造查询条件
     * @param string $where
     * @return array
     */
    public function initWhere (string $where){
        $ret = [];
        if (is_string($where)){
            $ret['status'] = 1;
            $arrWhere = explode('&',$where);
            if (isset($arrWhere[1]))
                $keywords = urldecode($arrWhere[1]);
            else
                $keywords = '';
            $ret['keywords'] = $keywords;

        }
        $this->requestWhere = $ret;
        return $ret;
    }

    /**
     * 构造when条件
     */
    private function whenWhere (string $key){
        if (isset($this->requestWhere[$key])){
            if (!empty($this->requestWhere[$key])){
                return true;
            }
        }
        return false;
    }

    /**
     * 统计漏洞数量
     * @param int $ckId
     * @param int $tId
     * @return int $c
     */
    public function vulNumOfCk ($ckId,$tId){
        $c = 0;
        if ($ckId > 0 && $tId > 0){

            $c = self::getBuilderForVul($ckId,$tId)->count();
        }
        return $c;
    }

    /**
     * 漏洞信息
     * @param int $ckId
     * @param int $tId
     * @return mixed
     */
    public static function vulListOfCk ($ckId,$tId){
        $list = collect();
        if ($ckId > 0 && $tId > 0){

            $list = self::getBuilderForVul($ckId,$tId)->get();
        }
        return $list;
    }

    /**
     * @param $ckId
     * @param $tId
     * @return mixed
     */
    public static function vulListOfCkHis ($ckId,$tId){
        $list = collect();
        if ($ckId > 0 && $tId > 0){

            $list = self::getBuilderForVul($ckId,$tId,false)->get();
        }
        return $list;
    }

    /**
     * @return mixed
     */
    public static function listForSelect (){
        $sel = ['id','name'];

        return self::select($sel)->get();
    }

    /**
     * @param $ckId
     * @param $tId
     * @param bool $between
     * @return $this
     */
    private static function getBuilderForVul ($ckId,$tId,$between=true){

        $builder = Vuls::select('vuls.*', 'users.real_name as uname', 'users.name as account', 'level.name as lname', 'app.name as aname', 'category.name as cname', 'users.source', 'app.ogz_id');
        $appId = DB::table('project_task_app')->where(['project_task_id'=>$tId])->value('app_id');
        $betweenTime = ProjectTask::select(['started_at','ended_at'])->where(['id'=>$tId])->first();
        $builder = $builder->leftjoin('users', 'users.id', '=', 'vuls.user_id')
            ->leftjoin('level', 'level.id', '=', 'vuls.level_id')
            ->leftjoin('app', 'app.id', '=', 'vuls.app_id')
            ->leftjoin('category', 'category.id', '=', 'vuls.category_id');
        $builder = $builder->where(['vuls.app_id'=>$appId,'vuls.check_id'=>$ckId]);
        if ($between){

            $builder = $builder->whereBetween('vuls.created_at',[$betweenTime->started_at,$betweenTime->ended_at]);
        }else{
            $builder = $builder->where('vuls.created_at','<=',$betweenTime->started_at);
        }
        return $builder;
    }

}